import base64
import os
from .file_utils import clean_path  # 导入路径清洗函数

def process_image(file_path, client):
    """
    处理图片并返回分析结果
    
    参数:
        file_path (str): 图片文件路径
        client (OpenAIClient): OpenAI客户端实例
    
    返回:
        str: 图片分析结果文本
    """
    # 清洗路径，去除首尾双引号和空格
    cleaned_path = clean_path(file_path)
    
    # 检查文件是否存在
    if not os.path.exists(cleaned_path):
        raise FileNotFoundError(f"图片文件不存在: {cleaned_path}")
    
    # 读取图片文件并转换为base64编码
    with open(cleaned_path, "rb") as image_file:
        image_data = image_file.read()
        image_base64 = base64.b64encode(image_data).decode("utf-8")
    
    # 获取文件扩展名（不带点）
    file_ext = os.path.splitext(cleaned_path)[1][1:].lower()
    
    # 使用 client.client 访问底层的 OpenAI 客户端
    response = client.client.chat.completions.create(
        model="moonshot-v1-8k-vision-preview",
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/{file_ext};base64,{image_base64}"
                    }
                },
                {"type": "text", "text": "请分析这张图片中的内容。"}
            ]
        }],
        temperature=0.3,
    )
    
    return response.choices[0].message.content